package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"go_self/model"
	"go_self/util"
	"strconv"
	"strings"
	"time"
)

// GoodsByAdd 商品录入
func GoodsByAdd(input map[string]string) error {
	if input["title"] == "" {
		return errors.New("标题不能为空")
	}
	if input["picture"] == "" {
		return errors.New("图片不少于一个")
	}
	if input["category_ids"] == "" {
		return errors.New("分类不能为空")
	}
	if input["sku_data"] == "" {
		return errors.New("sku不能为空")
	}
	if input["up_down"] == "" {
		input["up_down"] = strconv.Itoa(model.GoodsByUpDownNo)
	}

	//图片处理
	pictureSplit := strings.Split(input["picture"], ",")
	//时间
	thisTime := time.Now().Format(time.RFC3339)
	//分类
	categorySplit := strings.Split(input["category_ids"], ",")
	//sku解析成切片
	skuSplit := make([]map[string]interface{}, 0)
	err := json.Unmarshal([]byte(input["sku_data"]), &skuSplit)
	if err != nil {
		gogo_log.Write("server_GoodsByAdd", "商品录入失败1", err.Error())
		return errors.New("商品录入失败")
	}
	//获取sku里最大和最小价格
	goodsMax, goodsMin := model.SkuMaxOrMinByPrice(skuSplit)
	tx, _ := model.PgSql.Begin()
	defer tx.Rollback()
	//商品表信息表
	goods := make(map[string]interface{})
	//goods["shop_id"] = shopId
	goods["title"] = input["title"]
	goods["picture"] = pictureSplit[0]
	goods["category_one"] = categorySplit[0]
	goods["category_two"] = categorySplit[1]
	goods["max_price"] = goodsMax
	goods["min_price"] = goodsMin
	goods["up_down"] = input["up_down"]
	goods["is_hot"] = model.GoodsByIsHotNo
	goods["is_recommend"] = model.GoodsByIsRecommendNo
	goods["status"] = model.GoodsByStatusNormal
	goods["time_c"] = thisTime
	goods["time_u"] = thisTime

	goodsSql, args := sql_aid.PgTable(model.TableByGoods).InsertByMap(&goods)
	var goodsId int64
	err = tx.QueryRow(goodsSql+" RETURNING id", args...).Scan(&goodsId)
	if err != nil {
		gogo_log.Write("server_GoodsByAdd", "商品录入失败2", err.Error())
		return errors.New("商品录入失败")
	}
	//商品图片信息表
	for _, val := range pictureSplit {
		goodsPicture := make(map[string]interface{})
		goodsPicture["goods_id"] = goodsId
		goodsPicture["picture"] = val
		goodsPictureSql, args := sql_aid.PgTable(model.TableByGoodsPicture).InsertByMap(&goodsPicture)
		_, err = tx.Exec(goodsPictureSql, args...)
		if err != nil {
			return errors.New("商品图片添加失败")
		}
	}

	//商品详情信息表
	goodsInfo := make(map[string]interface{})
	goodsInfo["goods_id"] = goodsId
	goodsInfo["details"] = input["details"]
	goodsInfoSql, args := sql_aid.PgTable(model.TableByGoodsInfo).InsertByMap(&goodsInfo)
	_, err = tx.Exec(goodsInfoSql, args...)
	if err != nil {
		gogo_log.Write("server_GoodsByAdd", "商品录入失败3", err.Error())
		return errors.New("商品录入失败")
	}

	for _, val := range skuSplit {
		skuVal := make(map[string]interface{})
		//skuVal["shop_id"] = shopId
		skuVal["goods_id"] = goodsId
		jsonToSku, _ := json.Marshal(val["sku"])
		skuVal["sku"] = jsonToSku
		skuVal["number"] = val["number"]
		flo, _ := strconv.ParseFloat(val["price"].(string), 64)
		skuVal["price"] = flo
		skuVal["time_c"] = thisTime
		skuVal["picture"] = val["picture"].(string)
		goodsSkuSql, args := sql_aid.PgTable(model.TableByGoodsSku).InsertByMap(&skuVal)
		_, err = tx.Exec(goodsSkuSql, args...)
		if err != nil {
			return errors.New("商品sku添加失败")
		}
	}

	tx.Commit()
	return nil
}

// GoodsByList 商品列表
func GoodsByList(input map[string]string) []map[string]interface{} {
	if input["orderBy"] == "" { //默认排序
		input["orderBy"] = "id desc"
	}
	//排序
	goodsSql, arge := sql_aid.PgTable(model.TableByGoods).WhereRaw(func(query *sql_aid.PgQuery, i ...interface{}) {
		//if i[0].(map[string]string)["shop_id"] != "" { //店铺ID
		//	query.Where("title like ?", "%"+i[0].(map[string]string)["title"]+"%")
		//}
		if i[0].(map[string]string)["title"] != "" { //店铺ID
			query.Where("username like %?%", i[0].(map[string]string)["username"])
		}
		if i[0].(map[string]string)["up_down"] != "" { //上下架
			query.Where("up_down = ?", i[0].(map[string]string)["up_down"])
		}
		if i[0].(map[string]string)["is_hot"] != "" { //是否热门
			query.Where("is_hot = ?", i[0].(map[string]string)["is_hot"])
		}
		if i[0].(map[string]string)["is_recommend"] != "" { //是否推荐
			query.Where("is_recommend = ?", i[0].(map[string]string)["is_recommend"])
		}
		if i[0].(map[string]string)["status"] != "" { //状态
			query.Where("status = ?", i[0].(map[string]string)["status"])
		}
		if i[0].(map[string]string)["price"] != "" { //价格
			query.Where("max_price < ?", i[0].(map[string]string)["price"])
			query.Where("min_price > ?", i[0].(map[string]string)["price"])
		}
	}, input).Where("time_d is null", nil).OrderBy(input["orderBy"]).PageSize(input["page"], input["page_size"]).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Error("server_GoodsByList", "商品列表", err.Error())
		return []map[string]interface{}{}
	}
	return goodsData
}

// GoodsSearch 商品搜索
func GoodsSearch(goodsTitle string, input map[string]string) []map[string]interface{} {
	goodsSql, arge := sql_aid.PgTable(model.TableByGoods).Field("id", "title", "picture", "max_price", "min_price", "order_count", "click_count").Where("title like ?", "%"+goodsTitle+"%").Where("up_down = ?", model.GoodsByUpDownYes).Where("time_d is null", nil).OrderBy("order_count desc").PageSize(input["page"], input["page_size"]).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Error("server_GoodsSearch", "商品搜索", err.Error())
		return []map[string]interface{}{}
	}
	return goodsData

}

// GoodsByUpDown 批量更改商品上下架
func GoodsByUpDown(input map[string]string) error {
	goodsIdsBySplitString := strings.Split(input["goods_ids"], ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	update := make(map[string]interface{})
	if input["up_down"] == "1" {
		update["up_down"] = "1"
	} else {
		update["up_down"] = "0"
	}
	goodsUpdate, args := sql_aid.PgTable(model.TableByGoods).WhereIn("id", goodsIdsBySplitInterface...).UpdateByMap(&update)
	_, err := model.PgSql.Exec(goodsUpdate, args...)
	if err != nil {
		gogo_log.Write("server_GoodsByUpDown", "批量更改商品上下架1", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// GoodsToIsHot 批量更改商品热门
func GoodsToIsHot(shopId int64, input map[string]string) error {
	goodsIdsBySplitString := strings.Split(input["goods_ids"], ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	update := make(map[string]interface{})
	if input["is_hot"] == "1" {
		update["is_hot"] = "1"
	} else {
		update["is_hot"] = "0"
	}
	goodsUpdate, args := sql_aid.PgTable(model.TableByGoods).WhereIn("id", goodsIdsBySplitInterface...).Where("shop_id = ?", shopId).UpdateByMap(&update)
	_, err := model.PgSql.Exec(goodsUpdate, args...)
	if err != nil {
		gogo_log.Write("server_GoodsToIsHot", "批量更改商品热门1", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// GoodsToIsRecommend 批量更改商品推荐
func GoodsToIsRecommend(shopId int64, input map[string]string) error {
	goodsIdsBySplitString := strings.Split(input["goods_ids"], ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	update := make(map[string]interface{})
	if input["is_recommend"] == "1" {
		update["is_recommend"] = "1"
	} else {
		update["is_recommend"] = "0"
	}
	goodsUpdate, args := sql_aid.PgTable(model.TableByGoods).WhereIn("id", goodsIdsBySplitInterface...).Where("shop_id = ?", shopId).UpdateByMap(&update)
	_, err := model.PgSql.Exec(goodsUpdate, args...)
	if err != nil {
		gogo_log.Write("server_GoodsToIsRecommend", "批量更改商品推荐", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// GoodsToStatus 批量更改商品状态
func GoodsToStatus(shopId int64, input map[string]string) error {
	goodsIdsBySplitString := strings.Split(input["goods_ids"], ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	update := make(map[string]interface{})
	if input["status"] == "1" {
		update["status"] = "1"
	} else {
		update["status"] = "0"
	}
	goodsUpdate, args := sql_aid.PgTable(model.TableByGoods).WhereIn("id", goodsIdsBySplitInterface...).Where("shop_id = ?", shopId).UpdateByMap(&update)
	_, err := model.PgSql.Exec(goodsUpdate, args...)
	if err != nil {
		gogo_log.Write("server_GoodsToStatus", "批量更改商品状态1", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// GoodsByDel 商品软删除
func GoodsByDel(input map[string]string) error {
	goodsIdsBySplitString := strings.Split(input["goods_ids"], ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	update := make(map[string]interface{})
	update["time_d"] = time.Now().Format(time.RFC3339)
	goodsUpdate, args := sql_aid.PgTable(model.TableByGoods).WhereIn("id", goodsIdsBySplitInterface...).UpdateByMap(&update)
	_, err := model.PgSql.Exec(goodsUpdate, args...)
	if err != nil {
		gogo_log.Write("server_GoodsByDel", "商品软删除1", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// GoodsInfo 商品详情
func GoodsInfo(input map[string]string) (map[string]interface{}, error) {
	//商品信息
	goodsSql, arge := sql_aid.PgTable(model.TableByGoods).WhereId(input["goods_id"]).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Write("server_GoodsInfo", "商品详情1", err.Error())
		return nil, errors.New("内部错误")
	}
	if goodsData[0] == nil {
		return nil, errors.New("商品不存在")
	}
	//商品轮播图
	goodsPictureSql, arge := sql_aid.PgTable(model.TableByGoodsPicture).Where("goods_id = ?", input["goods_id"]).ToSql()
	goodsPictureData, err := sql_aid.DataToMap(model.PgSql.Query(goodsPictureSql, arge...))
	if err != nil {
		gogo_log.Write("server_GoodsInfo", "商品详情2", err.Error())
		return nil, errors.New("内部错误")
	}

	if goodsPictureData != nil {
		goodsData[0]["goods_picture"] = goodsPictureData
	} else {
		goodsData[0]["goods_picture"] = make([]int, 0)
	}
	//商品详情
	goodsInfoSql, arge := sql_aid.PgTable(model.TableByGoodsInfo).Where("goods_id = ?", input["goods_id"]).ToSql()
	goodsInfoData, err := sql_aid.DataToMap(model.PgSql.Query(goodsInfoSql, arge...))
	if err != nil {
		gogo_log.Write("server_GoodsInfo", "商品详情3", err.Error())
		return nil, errors.New("内部错误")
	}
	goodsData[0]["goods_info"] = goodsInfoData[0]
	//商品sku
	goodsSkuSql, arge := sql_aid.PgTable(model.TableByGoodsSku).Where("goods_id = ?", input["goods_id"]).ToSql()
	goodsSkuData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSkuSql, arge...))
	if err != nil {
		gogo_log.Write("server_GoodsInfo", "商品详情4", err.Error())
		return nil, errors.New("内部错误")
	}
	if goodsSkuData != nil {
		goodsData[0]["goods_sku"] = goodsSkuData
	} else {
		goodsData[0]["goods_sku"] = make([]int, 0)
	}

	return goodsData[0], nil

}

// GoodsByPriceAll 计算商品的价格 skuJson参数结构 [{"sku_id":"222","number":"10"},{"sku_id":"223","number":"20"}]
func GoodsByPriceAll(skuJson string) (map[string]interface{}, error) {
	skuDataArr := make([]map[string]interface{}, 0, 0)
	err := json.Unmarshal([]byte(skuJson), &skuDataArr)
	if err != nil {
		return nil, errors.New("数据解析错误")
	}
	//获取sku信息
	DataByGoodsSkuId := util.ArrayField(&skuDataArr, "sku_id")
	skuSql, args := sql_aid.PgTable(model.TableByGoodsSku).WhereIn("id", *DataByGoodsSkuId...).ToSql()
	skuData, err := sql_aid.DataToMap(model.PgSql.Query(skuSql, args...))
	if err != nil {
		gogo_log.Error("server_UserShoppingCrtByIdsStatistics", "获取sku商品信息失败", err.Error())
		return nil, errors.New("获取sku商品信息失败")
	}
	skuColumnIdData := util.ArrayColumnByInt64(&skuData, "id")
	//获取商品信息
	//shoppingCartDataByGoodsId := util.ArrayField(&skuData,"goods_id")
	//goodsSql,args := sql_aid.PgTable(model.TableByGoods).WhereIn("id",*shoppingCartDataByGoodsId...).ToSql()
	//goodsData,err := sql_aid.DataToMap(model.PgSql.Query(goodsSql,args...))
	//if err != nil {
	//	gogo_log.Error("server_UserShoppingCrtByIdsStatistics","获取商品信息失败",err.Error())
	//	return nil ,errors.New("获取商品信息失败")
	//}
	//goodsDataByColumnId := util.ArrayColumnByInt64(&goodsData,"id")
	//计算数据
	var priceAll = 0.00
	for _, val := range skuDataArr {
		setSkuData := skuColumnIdData[int64(val["sku_id"].(float64))]
		if setSkuData == nil {
			return nil, errors.New("数据错误")
		}
		//if util.StringToInt64(val["number"].(string)) > setSkuData["number"].(int64) {//判断
		//	goodsTitle := goodsDataByColumnId[setSkuData["goods_id"].(int64)]["title"].(string)
		//	goodsSkuNumber := setSkuData["number"].(int64)
		//	return nil ,errors.New(fmt.Sprintf("规格是'%v'的'%v'仅剩余%v件",setSkuData["sku_string"],goodsTitle,goodsSkuNumber))
		//}
		priceAll += util.StringToFloat64(setSkuData["price"].(string)) * val["number"].(float64)
	}
	priceAll, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", priceAll), 64)
	data := make(map[string]interface{})
	data["price_all"] = priceAll
	return data, nil
}
